﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Linq;
using System.ComponentModel;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YGRABDOC
    {
        VGABEW _GBW;
        public VGABEW GBW
        {
            get
            {
                if (_GBW == null) _GBW = new VGABEW();
                return _GBW;
            }
        }
        private void btnInitializedMU_Click(object sender, RoutedEventArgs e)
        {
            txtMessage.Visibility = Visibility.Visible;
            if (dwABPOS == null)
            {
                MessageBox.Show("请选择需要计划的生产单");
                return;
            }
            DataSet SResult;
            SetDetail.ICC_ABAX.Clear();
            //正对所有的单创建一个记录集合，针对每个单的记录集合，创建生产单
            try
            {
                SResult = m_Data.PrePlan(SetDetail, dwABPOS, IsRepair);

                string path = @"C:\IntexReport\Data\YGRMU";
                SResult.Tables["ABPOS"].TableName = "ABPOS_EXT";
                m_Data.ABP.Save2Xml(SResult, path);
                m_Data.ABP.AutoConvert(path, "YGRMUZT"); 
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                Tracer.Error(ex.StackTrace, ex);
                EventDispatcher.Instance.RaiseStatus("遇到问题:" + ex.Message + "终止", StatusEventType.StopProgress);
            }
            finally
            {
                SetDetail.Clear();
                if (IsRepair)
                {
                    MessageBox.Show("请记住分盘单号码，并对它进行分盘。");
                }
            }
        }

        private void btnRemoveBatch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int ABAAPOS = 0;
                string AAP = "";
                string filter = "";
                DataRow[] rows;
                #region====ICC_ABAX=======

                var qMU = from row in SetDetail.ICC_ABAX.AsEnumerable()
                          group row by new
                          {
                              KRS = row["ABAAUFKRS"].ToString(),
                              LFD = row["ABAAUFLFD"].ToString(),
                              POS = row["ABAAUFPOS"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString()) / 1000),
                                  ABAAPOS = g.Max(XD => Convert.ToInt16(XD["ABAAPOS"].ToString())),
                              };
                foreach (var mu in qMU)
                {
                    ABAAPOS = mu.ABAAPOS;
                    if (ABAAPOS == 2)
                    {
                        MessageBox.Show("最有一个，不可以在取消,若要继续删除，请使用根除功能");
                        return;
                    }
                    int ABALEAPOS = ABAAPOS - 1;
                    //find the row to split
                    AAP = Helpers.Helper.Right("0000" + ABAAPOS, 4);

                    var qExt = from DataRow row in SetDetail.ABAUFM.AsEnumerable()
                               where row["ABAAUFKRS"].ToString() == mu.KEY.KRS
                               && row["ABAAUFLFD"].ToString() == mu.KEY.LFD
                               && row["ABAAUFPOS"].ToString() == mu.KEY.POS
                               && Convert.ToInt16(row["ABAAPOS"].ToString()) == ABAAPOS
                               select row;
                    foreach (DataRow row in qExt)
                    {
                        decimal mqty = Convert.ToDecimal(row["ABARESMG"].ToString());
                        var qPre = from DataRow rPre in SetDetail.ABAUFM.AsEnumerable()
                                   where rPre["ABAAUFKRS"].ToString() == mu.KEY.KRS
                                   && rPre["ABAAUFLFD"].ToString() == mu.KEY.LFD
                                   && rPre["ABAAUFPOS"].ToString() == mu.KEY.POS
                                   && Convert.ToInt16(rPre["ABAAPOS"].ToString()) == ABAAPOS - 1
                                   select rPre;
                        foreach (DataRow rPre in qPre)
                        {
                            rPre["ABARESMG"] = Convert.ToDecimal(rPre["ABARESMG"].ToString()) + mqty;
                            INTEXDBC.UpdateABAUFM(rPre, 5);
                            INTEXDBC.DeleteABAUFM(row, 1);
                            row["ABAAPOS"] = "0001";
                            row["ABALEAPOS"] = ABALEAPOS;
                            INTEXDBC.UpdateABAUFM(row, 4);
                        }
                    }
                }
                #endregion
                filter = "ABAAPOS <>'" + AAP + "'";
                rows = SetDetail.ICC_ABAX.Select(filter);
                DataTable tb = rows.CopyToDataTable();
                tb.TableName = "ICC_ABAX";
                SetDetail.Tables["ICC_ABAX"].Clear();
                SetDetail.Merge(tb);
                SetDetail.AcceptChanges();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        Dictionary<string, object> PM = new Dictionary<string, object>();
        private void btnRemoveMU_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwMU == null)
                {
                    MessageBox.Show("请选择最大的分批号");
                    return;
                }
                foreach (DataRow ROW in SetDetail.ICC_ABAX.Rows)
                {
                    if (Convert.ToInt16(ROW["ABAAPOS"].ToString()) > 2)
                    {
                        MessageBox.Show("请选择最大的分批号");
                        return;
                    }
                }
                string HMKRS = "", HMLFD = "", HMPOS = "", UPOS = "";
                string _fpkrs = "", _fplfd = "", _fppos = "";
                DataSet SResult;
                DataRow dwData = SetData.ICC_QUERYTB.NewRow();
                _fpkrs = dwMU["ABAAUFKRS"].ToString();
                _fplfd = dwMU["ABAAUFLFD"].ToString();
                _fppos = dwMU["ABAAUFPOS"].ToString();
                dwData["GAMANDANT"] = dwMU["ABAMANDANT"];
                dwData["GAAUFKRS"] = dwMU["ABAAUFKRS"];
                dwData["GAAUFLFD"] = dwMU["ABAAUFLFD"];
                SResult = INTEXDBC.QueryGAAUF(dwData, 6);

                foreach (DataRow mu in SetDetail.ICC_ABAX.Rows)
                {
                    _fpkrs = mu["ABAAUFKRS"].ToString();
                    _fplfd = mu["ABAAUFLFD"].ToString();
                    _fppos = mu["ABAAUFPOS"].ToString();
                    HMKRS = mu["ABAVKAUFKRS"].ToString();
                    HMLFD = mu["ABAVKAUFLFD"].ToString();
                    HMPOS = mu["ABAVKAUFPOS"].ToString();
                    UPOS = mu["ABAVKUPOS"].ToString();
                    string ABAART = mu["ABPART"].ToString();
                    string ABAVAR = mu["ABPVAR"].ToString();
                    string ABAFARBE = mu["ABPFARBE"].ToString();

                    var qGA = from DataRow dwGA in SResult.Tables[0].AsEnumerable()
                              where dwGA["GAAUFKRS"].ToString() == _fpkrs
                              && dwGA["GAAUFLFD"].ToString() == _fplfd
                              && dwGA["GAAUFPOS"].ToString() == _fppos
                              && dwGA["GASA"].ToString() == "713"
                              select dwGA;
                    foreach (DataRow dwGA in qGA)
                    {
                        dwGA["GAAUFKRS"] = HMKRS;
                        dwGA["GAAUFLFD"] = HMLFD;
                        dwGA["GAAUFPOS"] = HMPOS;
                        dwGA["GAPOS"] = UPOS;
                        INTEXDBC.UpdateGAAUF(dwGA, 10);
                    }
                    
                    var qZU = from DataRow ZU in SetDetail.Tables["ZUTEI_EXT"].AsEnumerable()
                              where ZU["ZUAUFKRS"].ToString() == _fpkrs
                              && ZU["ZUAUFLFD"].ToString() == _fplfd
                              && ZU["ZUAUFPOS"].ToString() == _fppos
                              && ZU["ZUSA"].ToString() == "713"
                              select ZU;
                    foreach (DataRow dwZU in qZU)
                    {
                        dwZU["ZUAUFKRS"] = HMKRS;
                        dwZU["ZUAUFLFD"] = HMLFD;
                        dwZU["ZUAUFPOS"] = HMPOS;
                        dwZU["ZUPOS"] = UPOS;
                        GBW.NWBBEW(dwZU, "61", "123");
                        INTEXDBC.SaveZUTEI(dwZU, "YGR");
                    }
                }
                PM["KRS"] = _fpkrs;
                PM["LFD"] = _fplfd;
                PM["POS"] = _fppos;
                m_Data.ZU.RVZUTEI(PM);
                dwData["ABPMANDANT"] = app.Mandant;
                dwData["ABPAUFKRS"] = HMKRS;
                dwData["ABPAUFLFD"] = HMLFD;
                dwData["ABPAUFPOS"] = HMPOS;
                INTEXDBC.UpdateABPOS(dwData, 6);
                INTEXBL.DELTEABPOS("00", _fpkrs, _fplfd, "000");
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                SetDetail.Clear();
                btnQuery_Click(null, null);
            }
        }
        //原有缸的分盘数和单盘重
        private void NewBatch(decimal batchqty, decimal batches)
        {
            decimal ratio = 1;
            decimal MQTY = 1;
            try
            {
                string CABAAPOS = dwMU["ABAAPOS"].ToString();
                var qMU = from row in SetDetail.ICC_ABAX.AsEnumerable()
                          group row by new
                          {
                              KRS = row["ABAAUFKRS"].ToString(),
                              LFD = row["ABAAUFLFD"].ToString(),
                              ABAAPOS = row["ABAAPOS"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString()) / 1000),
                              };
                foreach (var mu in qMU)
                {
                    if (mu.KEY.ABAAPOS == CABAAPOS)
                    {
                        MQTY = mu.MQTY;
                        ratio = batchqty / MQTY;
                    }
                }
                var qMUMx = from row in SetDetail.ICC_ABAX.AsEnumerable()
                            group row by new
                            {
                                KRS = row["ABAAUFKRS"].ToString(),
                                LFD = row["ABAAUFLFD"].ToString(),
                                POS = row["ABAAUFPOS"].ToString(),
                            }
                                into g
                                select new
                                {
                                    KEY = g.Key,
                                    MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString()) / 1000),
                                    ABAAPOS = g.Max(XD => Convert.ToInt16(XD["ABAAPOS"].ToString())),
                                };
                int ABALEAPOS = 2;
                int ABAAPOS = 2;
                foreach (var mu in qMUMx)
                {
                    ABAAPOS = mu.ABAAPOS;
                    ABALEAPOS = ABAAPOS + 1;
                }
                //find the row to split
                var qExt = from DataRow row in SetDetail.ABAUFM.AsEnumerable()
                           where row["ABAAUFKRS"].ToString() == dwMU["ABAAUFKRS"].ToString()
                           && row["ABAAUFLFD"].ToString() == dwMU["ABAAUFLFD"].ToString()
                           && row["ABAAPOS"].ToString() == CABAAPOS
                           select row;
                foreach (DataRow row in qExt)
                {
                    if (row["ABASANZSTK"].ToString().Trim() == "")
                        row["ABASANZSTK"] = "1";
                    batches = Convert.ToDecimal(row["ABAVKFARBE"].ToString());
                    decimal mqty = Convert.ToDecimal(row["ABARESMG"].ToString()) / 1000;
                    DataRow nMu = INTEXDBC.Convert2ABAUFM(row, "YGR", true);//现在的留位行，表达为新增数量

                    nMu["ABARESMG"] = Math.Round(mqty * ratio * 1000 / 10) * 10;
                    nMu["ABASANZSTK"] = 1;//分缸数
                    nMu["ABASSTKGEW"] = nMu["ABARESMG"];//单盘重量
                    INTEXDBC.UpdateABAUFM(nMu, 3);
                    nMu = INTEXDBC.Convert2ABAUFM(row, "YGR", true);//新的留位行
                    nMu["ABARESMG"] = Math.Round(mqty * (1 - ratio) * 1000 / 10) * 10;
                    decimal ABARESMG = Convert.ToDecimal(nMu["ABARESMG"].ToString());
                    batchqty = Math.Round((ABARESMG / 10) / batches, 0) * 10;
                    nMu["ABASANZSTK"] = 1;//分缸数
                    nMu["ABASSTKGEW"] = Helpers.Helper.Left(batchqty.ToString().PadRight(20), 20);//单盘重量
                    nMu["ABAAPOS"] = Helpers.Helper.Right("0000" + (ABALEAPOS).ToString(), 4);
                    INTEXDBC.SaveABAUFM(nMu, "YGR");
                    nMu["ABAAPOS"] = "0001";
                    nMu["ABALEAPOS"] = ABALEAPOS;
                    INTEXDBC.UpdateABAUFM(nMu, 4);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        private void UpdateBatches(decimal batches)
        {
            string ABAAPOS = "";
            try
            {
                var qMU = from row in SetDetail.ICC_ABAX.AsEnumerable()
                          where row["ABAAPOS"].ToString() == dwMU["ABAAPOS"].ToString()
                          select row;
                foreach (var mu in qMU)
                {
                    decimal ABARESMG = Convert.ToDecimal(mu["ABARESMG"].ToString());
                    decimal targetmqty = Math.Round(ABARESMG / Batches, 0);
                    mu["ABASANZSTK"] = batches;
                    mu["ABASSTKGEW"] = targetmqty;
                    ABAAPOS = dwMU["ABAAPOS"].ToString();
                    //find the row to split
                    var qExt = from DataRow row in SetDetail.ABAUFM.AsEnumerable()
                               where row["ABAAUFKRS"].ToString() == mu["ABAAUFKRS"].ToString()
                               && row["ABAAUFLFD"].ToString() == mu["ABAAUFLFD"].ToString()
                               && row["ABAAUFPOS"].ToString() == mu["ABAAUFPOS"].ToString()
                               && row["ABAAPOS"].ToString() == ABAAPOS
                               select row;
                    foreach (DataRow row in qExt)
                    {
                        row["ABASANZSTK"] = batches;//分缸数
                        row["ABASSTKGEW"] = targetmqty;//单盘重量
                        INTEXDBC.UpdateABAUFM(row, 3);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        private void btnAddBatch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwTABPOS == null)
                {
                    MessageBox.Show("请选择生产单行");
                    return;
                }
                if (BatchQty == 0)
                {
                    MessageBox.Show("请确定分盘(产品)数量");
                    return;
                }
                int batchnum = 1;
                NewBatch(BatchQty, 1);//增加一个分批时，分缸数是1;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                btnQuery_Click(null, null);
            }
        }

        private void btnSaveBatch_Click(object sender, RoutedEventArgs e)
        {
            if (dwMU == null)
                return;
            UpdateBatches(Batches);
        }

    }
}
